<?php
namespace app\common\service;

use app\common\model\ProductCat as ProductCatModel;
use app\common\tool\Tool;
use think\Loader;


class ProductCat{


    public function find($id){
        return ProductCatModel::get($id);
    }

    public function all(){
        $productCatModel = new ProductCatModel();
        return $productCatModel->all();
    }


    public function allByCatWay($catWay = 'sys'){

        $productCatModel = new ProductCatModel();

        return $productCatModel -> where('catway',$catWay)->select();
    }

    public function treeByCatWay($catWay = 'sys'){
        $menus = ProductCatModel::where('catway',$catWay)->select();
        $menus = collection($menus)->toArray();
        $menusById = [];
        foreach($menus as $val){
            $menusById[$val['id']] = $val;
        }
        $tree = Tool::findSub($menusById,0);
        return $tree;
    }

    public function insert($data){

        $productCatModel = new ProductCatModel();

        $validate = Loader::validate("ProductCatValidate");
        $checkResult = $validate ->scene("add") -> check($data);
        if(!$checkResult){
            return ['state'=>0,'message'=>$validate->getError()];
        }

        $result = $productCatModel->allowField(['name','catway'])->save($data);

        if(false === $result){

            return ['state'=>0,'message'=>$productCatModel->getError()];
        }

        return ['state'=>1,'message'=>'','insertId'=>$productCatModel->id];

    }


    public function update($data){


    }

    /**
     * 删除一个
     * @param $id
     * @return int
     */
    public function delete($id){

        $productCatModel = new ProductCatModel();

        $count = $productCatModel ->destroy([$id]);

        return $count;
    }

}